package com.sense.kukoo.common.repo.http

import android.os.Build
import android.text.TextUtils
import com.sense.kukoo.common.R
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.utils.AppUtil
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.utils.PhoneUtil
import com.sense.kukoo.common_i18n.I18n
import com.sense.kukoo.lib_logger.LoggerManager
import okhttp3.*
import okio.Buffer
import java.lang.IllegalStateException
import java.lang.StringBuilder
import java.nio.charset.Charset
import java.security.MessageDigest
import java.util.*
import kotlin.collections.HashMap
import kotlin.random.Random

/**
 * </br> ClassName:   ClientAuthInterceptor.java
 *</br> Description: Http请求拦截
 * </br> Author:      lionszhang
 * </br> Date:        2021/11/12
 */
class KukooInterceptor private constructor() : Interceptor {

    private val TAG: String = javaClass.simpleName

    private val mDeviceNo: String
    private val mVersion: String

    init {
        mDeviceNo = PhoneUtil.getDeviceID(ApplicationContext.instance())
        mVersion = AppUtil.getAppVersion(false)
    }

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { KukooInterceptor() }

        private val chs =
            arrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')

        private fun str2Md5(str: String): String {
            val messageDigest: MessageDigest
            try {
                messageDigest = MessageDigest.getInstance("MD5")
            } catch (e: Exception) {
                throw IllegalStateException(e)
            }
            val bys = messageDigest.digest(str.toByteArray())
            val sb = StringBuilder(32)
            var index = 0
            for (b: Byte in bys) {
                index = b.toInt()
                if (index < 0) {
                    index += 256
                }
                if (index < 16) {
                    sb.append('0')
                }
                sb.append(Integer.toHexString(index))
            }
            return sb.toString()
        }
    }

    @Throws(Exception::class)
    override fun intercept(chain: Interceptor.Chain): Response? {
        val requestBuilder = chain.request().newBuilder()
        requestBuilder.addHeader("Content-Type", "application/json")

        val timeZone = Calendar.getInstance().timeZone.getDisplayName(false, TimeZone.SHORT)
        val localeSTR = I18n.getLocaleString(ApplicationContext.instance())

        requestBuilder.addHeader("clientId", PhoneUtil.getDeviceID(ApplicationContext.instance()))
        requestBuilder.addHeader("locale", localeSTR )
        requestBuilder.addHeader("timeZone", timeZone )
        val accessToken = Repo.login.get()?.accessToken
        if(!TextUtils.isEmpty(accessToken)){
            val Authorization = "Bearer ${accessToken}"
            requestBuilder.addHeader("Authorization", Authorization)
        }
        requestBuilder.addHeader("clientType", "2")//终端类型: 1. 苹果; 2. 安卓;

        val newRequest = requestBuilder.build()
        val requestBody = newRequest.body()
        val body = requestBody.let {
            val buffer = Buffer()
            it?.writeTo(buffer)
            var defaultCharset = Charset.defaultCharset()
            var contentType = it?.contentType()
            var charset = contentType?.charset(defaultCharset)
            buffer.readString(charset ?: defaultCharset)
        }

        LoggerManager.d(TAG, "Request-star -> ${newRequest.method()}:${newRequest.url()}")
        LoggerManager.d(TAG, "headers -> \n${newRequest.headers()}")
        LoggerManager.json(TAG, body)

        val t1 = System.currentTimeMillis()
        val response = chain.proceed(newRequest)
        val t2 = System.currentTimeMillis()
        LoggerManager.d(TAG, "Received response for ${t2 - t1}ms")

        val responseBody = response.peekBody(Long.MAX_VALUE).string()
        LoggerManager.json(TAG, responseBody)

        return response
    }
}
